<?php

namespace app\admin\controller\yxerp\code;

use app\common\controller\Backend;
use think\facade\Db;
/**
 * 编码规则
 */
class Rule extends Backend
{
    /**
     * Rule模型对象
     * @var object
     * @phpstan-var \app\admin\model\yxerp\code\Rule
     */
    protected object $model;
    protected object $model_log;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\yxerp\code\Rule();
        $this->model_log = new \app\admin\model\yxerp\code\Log();
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    // 获取自动编码
    public function getNextCode()
    {
        $codeType = $this->request->param('code_type', '', 'trim');

        if (empty($codeType)) {
            return json(['code' => 0, 'msg' => '编码类型不能为空']);
        }
        // 启动事务
        Db::startTrans();
        try {
            // 锁定行读取规则
            $rule = $this->model
                ->where('code_type', $codeType)
                ->where('status', 1)
                ->lock(true)
                ->find();

            if (!$rule) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '未找到编码规则']);
            }
            $current = $rule['current_number'] + 1;
            // 生成编码
            $numberStr = str_pad($current, $rule['length'], '0', STR_PAD_LEFT);
            $code = $rule['prefix'] . ($rule['separator'] ?? '') . $numberStr;

            $this->model_log->insert([
                'code_type' => $codeType,
                'code'      => $code,
                'status'    => 0, // 未使用
                'create_time' => date('Y-m-d H:i:s')
            ]);
            Db::commit();
           return json(['code' => 1, 'msg' => '获取成功', 'data' => $code]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 0, 'msg' => '编码生成失败：' . $e->getMessage()]);
        }
    }

    public function getCode()
    {
        $codeType = $this->request->param('code_type', '', 'trim');
        if (!$codeType) {
            return json(['code' => 0, 'msg' => '参数 code_type 必填']);
        }

        // 从数据库读取编号规则
        $rule = $this->model
            ->where('code_type', $codeType)
            ->find();

        if (!$rule) {
            return json(['code' => 0, 'msg' => '未找到该编码类型的规则']);
        }

        $prefix       = $rule->prefix ?? '';                  // 前缀
        $length       = intval($rule->length ?? 5);           // 位数
        $current      = intval($rule->current_number ?? 0);   // 当前编号
        $dateFormat   = trim($rule->date_format ?? '');       // 日期格式（如 Ymd）

        $newNumber    = $current + 1;
        $numberStr    = str_pad($newNumber, $length, '0', STR_PAD_LEFT);
        $dateStr      = $dateFormat ? date($dateFormat) : ''; // 根据规则生成日期字符串

        $code = $prefix . $dateStr . $numberStr;

        return json([
            'code' => 1,
            'msg'  => 'success',
            'data' => $code
        ]);
    }




}